const cheerio = require("cheerio");
const superagent = require("superagent");
const fs = require("fs");
const path=require('path')

// 
var douban=function(){
  this.getTags=function (type){
    var tagsUrl=encodeURI('https://movie.douban.com/j/search_tags?type='+type+'&source=');
    return new Promise((resolve,reject)=>{
      superagent.get(tagsUrl).end((err,res)=>{
        console.log(JSON.stringify(res.text))
      })
    })
  }
  // tags:[\"热门\",\"最新\",\"经典\",\"可播放\",\"豆瓣高分\",\"冷门佳片\",\"华语\",\"欧美\",\"韩国\",\"日本\",\"动作\",\"喜剧\",\"爱情\",\"科幻\",\"悬疑\",\"恐怖\",\"成长\"]
 this.getMovieList =function(tag,page_start){
    var movieUrl='https://movie.douban.com/j/search_subjects?type=movie&tag='+encodeURIComponent(tag)+'&page_limit=24&page_start='+page_start;
    console.log(movieUrl)
    return new Promise((resolve, reject) => {
      superagent
        .get(movieUrl)
        .end((err, res) => {
          if (err) reject("request error");
          const $ = cheerio.load(res.text);
          var text=JSON.parse(res.text);
          text['subjects'].length?resolve(text['subjects']):reject('没有找到，待会再试试')
        });
    });
  }
  // {\"tags\":[\"热门\",\"美剧\",\"英剧\",\"韩剧\",\"日剧\",\"国产剧\",\"港剧\",\"日本动画\",\"综艺\",\"纪录片\"]}
  this.getTvList=function(tag,page_start){
    var tvURL = "https://movie.douban.com/j/search_subjects?type=tv&tag="+encodeURIComponent(tag)+"&sort=recommend&page_limit=24&page_start="+page_start
    return new Promise((resolve, reject) => {
      superagent
        .get(tvURL)
        .end((err, res) => {
          if (err) reject("request error");
          const $ = cheerio.load(res.text);
          var text=JSON.parse(res.text);
          text['subjects'].length?resolve(text['subjects']):reject('没有找到，待会再试试')
        });
    });
  }
  
  this.saveFile=function(list,fileName){
    // 将传入的Json对象序列化
    var json=''
    for(let i=0;i<list.length;i++){
      json+=(JSON.stringify(list[i]) +',');
    }
    console.log(json)
    if(json){
      if(fs.existsSync(path.resolve(__dirname,'./'+fileName))){
        fs.appendFileSync(`${__dirname+'/'+fileName}`,json,'utf-8')
        console.log('追加数据')
      }else{
        fs.writeFileSync(`${__dirname+'/'+fileName}`,json,'utf-8')
        console.log('创建文件')
      }
    }
    
  }
}
const Douban=new douban();
 module.exports=Douban

// getMovieList("热门",0).then((res)=>{
// saveFile(res,'hotMovies.json')
// });

// getTvList("美剧",20).then((res)=>{
//   saveFile(res,'tv.json')
// })

// getTags('tv')

